/**
 * 
 */
package org.xelnaga.defiler.web.macro.variable;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.xelnaga.defiler.business.APILocator;
import org.xelnaga.defiler.business.ContentletAPI;
import org.xelnaga.defiler.business.FolderAPI;
import org.xelnaga.defiler.business.PreferenceAPI;

import freemarker.core.Environment;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateCollectionModel;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelIterator;

/**
 * @author qijb
 *
 */
public class VariableMacroHelper {
//	private HttpServletRequest request;
	private APILocator apiLocator;
	private CommonMacroHelper commonMacroHelper;
//	private Map<String, Object> model;
	/**
	 * @param model 
	 * @param applicationContext 
	 * @param request 
	 * 
	 */
	public VariableMacroHelper(HttpServletRequest request, APILocator apiLocator, Map<String, Object> model) {
//		this.request = request;
		this.apiLocator = apiLocator;
		this.commonMacroHelper = new CommonMacroHelper(request);
//		this.model = model;
	}
	public PreferenceAPI getPreferenceAPI() {
		return apiLocator.getPreferenceAPI();
	}
	public ContentletAPI getContentletAPI(){
		return apiLocator.getContentletAPI();
	}
	
	public FolderAPI getFolderAPI() {
		return apiLocator.getFolderAPI();
	}
	
	public ExposeAsVariablesDirective getExposeAsVariablesDirective() {
		return new ExposeAsVariablesDirective();
	}
	
	public static class ExposeAsVariablesDirective implements TemplateDirectiveModel {
		@SuppressWarnings("rawtypes")
		public void execute(Environment env, Map params,
				TemplateModel[] loopVars, TemplateDirectiveBody body)
				throws TemplateException, IOException {
			
			Object param = params.values().iterator().next();
			if (param instanceof SimpleHash) {
				SimpleHash hash = (SimpleHash) param;
				TemplateCollectionModel keys = hash.keys();
				TemplateModelIterator it = keys.iterator();
				while(it.hasNext()) {
					TemplateModel model = it.next();
					System.err.println(model.toString() + " ---  " + hash.get(model.toString()));
					env.setVariable(model.toString(), hash.get(model.toString())); 					
				}
//				Map map = ((SimpleHash) param).toMap();
//				Iterator it = map.entrySet().iterator();
//				while (it.hasNext()) {
//					Map.Entry entry = (Map.Entry) it.next();
//					TemplateModel model = objectWrapper.wrap(entry.getValue());
//					env.setVariable((String) entry.getKey(), model); 
//				}
			}
		}
	}

	public CommonMacroHelper getCommonMacroHelper() {
		return commonMacroHelper;
	}
	
}
